<style scoped>
  @import './log.less';
</style>
<template>
  <div>
    <Row>
      <Col span="24">
        <Card style="margin-bottom: 10px">
          <Form inline>
            <FormItem style="margin-bottom: 0">
              <Select v-model="searchConf.type" clearable placeholder="请选择类别" style="width:100px">
                <Option :value="1">文件名称</Option>
                <Option :value="2">文件位置</Option>
              </Select>
            </FormItem>
            <FormItem style="margin-bottom: 0">
              <Input v-model="searchConf.keywords" placeholder=""></Input>
            </FormItem>
            <FormItem style="margin-bottom: 0">
              <Button type="primary" @click="search">{{ $t('find_button') }}/{{ $t('refresh_button') }}</Button>
            </FormItem>
          </Form>
        </Card>
      </Col>
    </Row>
    <Row>
      <Col span="24">
        <Card>
          <p slot="title" style="height: 32px">
            <Button type="primary" @click="addModal" icon="md-add">{{ $t('add_button') }}</Button>&nbsp;
          </p>
          <div>
            <Table :loading="listLoading" :columns="columnsList" :data="tableData" border disabled-hover></Table>
          </div>
          <div class="margin-top-15" style="text-align: center">
            <Page :total="tableShow.listCount" :current="tableShow.currentPage"
                  :page-size="tableShow.pageSize" @on-change="changePage"
                  @on-page-size-change="changeSize" show-elevator show-sizer show-total></Page>
          </div>
        </Card>
      </Col>
    </Row>
    <Modal  v-model="modalSetting.show" width="30%" :styles="{top: '30px'}">
      <p slot="header" style="color:#2d8cf0">
        <Icon type="md-alert" />
        <span>新增附件</span>
      </p>
      <Row>
        <Form ref="myForm" :label-width="100">
          <FormItem label="选择文件" prop="file">
            <Upload type="drag"
                    ref="attachment"
                    :action="uploadUrl"
                    :headers="uploadHeader"
                    name="file"
                    :data="fileData"
                    :max-size="50120"
                    :on-success="handleImgSuccess"
                    :on-format-error="handleImgFormatError"
                    :on-exceeded-size="handleImgMaxSize"
                    :before-upload="handleUpload"
                    style="display: inline-block;">
              <div style="width: 58px;height:58px;line-height: 58px;margin:0 auto">
                <Icon type="md-add" size="20"></Icon>
              </div>
            </Upload>
          </FormItem>
        </Form>
      </Row>
      <div slot="footer">
        <Button type="primary" @click="cancel" style="margin-right: 8px">完成</Button>
      </div>
    </Modal>
  </div>
</template>
<script>
import CryptoJS from 'crypto-js'
import { baseUrl } from '@/libs/api.request'
import { getToken } from '@/libs/util'
import expandRow from './table_expand.vue'

const deleteButton = (vm, h, currentRow, index) => {
  return h('Poptip', {
    props: {
      confirm: true,
      title: '您确定要删除这条数据吗? ',
      transfer: true
    },
    on: {
      'on-ok': () => {
        vm.$easyAjax({ url: 'Attachment/delete/' + (currentRow.id), method: 'delete' }).then(response => {
          vm.getList()
          currentRow.loading = false
        })
      }
    }
  }, [
    h('Button', {
      style: {
        margin: '0 5px'
      },
      props: {
        type: 'error',
        placement: 'top',
        loading: currentRow.isDeleting
      }
    }, vm.$t('delete_button'))
  ])
}
export default {
  name: 'attachments',
  components: { expandRow },
  data () {
    return {
      listLoading: false,
      columnsList: [
        {
          title: 'ID',
          align: 'center',
          key: 'id',
          width: 100
        },
        {
          title: '文件名称',
          align: 'center',
          key: 'original_name'
        },
        {
          title: '类型',
          align: 'center',
          key: 'type',
          width: 120
        },
        {
          title: '大小（Mb）',
          align: 'center',
          width: 120,
          render: (h, params) => {
            return h('span', ((params.row.size) / 1000000).toFixed(3))
          }
        },
        {
          title: '存放位置',
          align: 'center',
          maxWidth: 500,
          tooltip: true,
          key: 'path'
        },
        {
          title: '创建时间',
          align: 'center',
          width: 180,
          key: 'create_time'
        },
        {
          title: '操作',
          align: 'center',
          width: 120,
          render: (h, params) => {
            return h('div', [
              deleteButton(this, h, params.row, params.index)
            ])
          }
        }
      ],
      uploadUrl: baseUrl + 'Attachment/add',
      fileData: { hash: '' },
      uploadHeader: { 'App-Login-Token': getToken() },
      tableData: [],
      tableShow: {
        currentPage: 1,
        pageSize: 10,
        listCount: 0
      },
      searchConf: {
        type: '',
        keywords: '',
        status: ''
      },
      modalSetting: {
        show: false,
        loading: false,
        index: 0
      },
      uploadLoading: null
    }
  },
  created () {
    this.getList()
  },
  methods: {
    addModal () {
      this.modalSetting.show = true
    },
    cancel () {
      this.modalSetting.show = false
    },
    handleUpload (file) {
      let vm = this
      let reader = new FileReader()
      reader.readAsArrayBuffer(file)
      reader.onload = function (evt) {
        var fileString = evt.target.result
        var wordArray = CryptoJS.lib.WordArray.create(fileString)
        var hash = CryptoJS.SHA256(wordArray).toString()
        vm.fileData.hash = hash
        vm.$easyAjax({ url: 'Attachment/add', data: { hash: hash }, method: 'post' }).then(res => {
          if (res.data.code) {
            vm.$Message.success({ content: '极速闪传成功' })
            vm.getList()
          } else {
            vm.autoUpload(file)
          }
        })
      }
      return false
    },
    autoUpload (file) {
      this.uploadLoading = this.$Message.loading({
        content: '上传中...',
        duration: 0
      })
      this.$refs.attachment.post(file)
    },
    handleImgFormatError (file) {
      this.$Notice.warning({
        title: '文件类型不合法',
        desc: file.name + '的文件类型不正确，请上传jpg或者png图片。'
      })
    },
    handleImgSuccess (response) {
      this.uploadLoading()
      if (response.code === 1) {
        this.$Message.success(response.msg)
        this.getList()
      } else {
        this.$Message.error(response.msg)
      }
    },
    handleImgMaxSize (file) {
      this.$Notice.warning({
        title: '文件大小不合法',
        desc: file.name + '太大啦请上传小于50M的文件。'
      })
    },
    changePage (page) {
      this.tableShow.currentPage = page
      this.getList()
    },
    changeSize (size) {
      this.tableShow.pageSize = size
      this.getList()
    },
    search () {
      this.tableShow.currentPage = 1
      this.getList()
    },
    getList () {
      let vm = this
      let params = {
        page: vm.tableShow.currentPage,
        size: vm.tableShow.pageSize,
        type: vm.searchConf.type,
        keywords: vm.searchConf.keywords
      }
      vm.listLoading = true
      this.$easyAjax({ url: 'Attachment/index', data: params }).then(response => {
        vm.listLoading = false
        vm.tableData = response.data.data.list
        vm.tableShow.listCount = response.data.data.count
      })
    }
  }
}
</script>
